package com.example.springbootapi.service.impl;

import com.example.springbootapi.entity.User;
import com.example.springbootapi.dto.UserDTO;
import com.example.springbootapi.vo.UserVO;
import com.example.springbootapi.mapper.UserMapper;
import com.example.springbootapi.service.UserService;
import com.example.springbootapi.common.PageResult;
import com.example.springbootapi.common.BusinessException;
import com.example.springbootapi.common.ErrorCode;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表（存储用户基础信息） 服务实现类
 * 
 * @author 开发者
 * @version 1.0.0
 * @since 2025-10-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public PageResult<UserVO> page(Integer pageNum, Integer pageSize, UserDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 动态查询条件构建
        if (queryDTO != null) {
            // 用户名（唯一，用于登录）查询条件
            if (StringUtils.hasText(queryDTO.getUsername())) {
                queryWrapper.like(User::getUsername, queryDTO.getUsername());
            }
            // 手机号（唯一，用于登录/验证）查询条件
            if (StringUtils.hasText(queryDTO.getPhone())) {
                queryWrapper.like(User::getPhone, queryDTO.getPhone());
            }
            // 密码（加密存储，如BCrypt算法）查询条件
            if (StringUtils.hasText(queryDTO.getPassword())) {
                queryWrapper.like(User::getPassword, queryDTO.getPassword());
            }
            // 真实姓名（用于收货/实名认证）查询条件
            if (StringUtils.hasText(queryDTO.getRealName())) {
                queryWrapper.like(User::getRealName, queryDTO.getRealName());
            }
            // 用户头像URL（如OSS存储地址）查询条件
            if (StringUtils.hasText(queryDTO.getAvatar())) {
                queryWrapper.like(User::getAvatar, queryDTO.getAvatar());
            }
            // 用户状态（1&#x3D;正常，0&#x3D;禁用）查询条件
            if (queryDTO.getUserStatus() != null) {
                queryWrapper.eq(User::getUserStatus, queryDTO.getUserStatus());
            }
            // 逻辑删除（0&#x3D;未删除，1&#x3D;已删除）查询条件
            if (StringUtils.hasText(queryDTO.getIsDeleted())) {
                queryWrapper.eq(User::getIsDeleted, queryDTO.getIsDeleted());
            }
            // 创建时间（用户注册时间）查询条件
            if (queryDTO.getCreateTime() != null) {
                queryWrapper.eq(User::getCreateTime, queryDTO.getCreateTime());
            }
            // 更新时间（自动更新）查询条件
            if (queryDTO.getUpdateTime() != null) {
                queryWrapper.eq(User::getUpdateTime, queryDTO.getUpdateTime());
            }
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc(User::getCreateTime);
        
        // 分页查询
        IPage<User> page = new Page<>(pageNum, pageSize);
        IPage<User> result = this.page(page, queryWrapper);
        
        // 转换为VO
        List<UserVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.<UserVO>builder()
                .records(voList)
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();
    }

    @Override
    public UserVO getById(Long id) {
        User entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户表（存储用户基础信息）不存在");
        }
        return convertToVO(entity);
    }

    @Override
    public UserVO create(UserDTO DTO) {
        // 参数验证
        validateDTO(DTO);
        
        // 转换为实体
        User entity = convertToEntity(DTO);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.save(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "创建用户表（存储用户基础信息）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public UserVO update(Long id, UserDTO DTO) {
        // 检查记录是否存在
        User existingEntity = this.getById(id);
        if (existingEntity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户表（存储用户基础信息）不存在");
        }
        
        // 参数验证
        validateDTO(DTO);
        
        // 更新实体
        User entity = convertToEntity(DTO);
        entity.setId(id);
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.updateById(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "更新用户表（存储用户基础信息）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public void delete(Long id) {
        // 检查记录是否存在
        User entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户表（存储用户基础信息）不存在");
        }
        
        // 删除
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "删除用户表（存储用户基础信息）失败");
        }
    }

    @Override
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "删除ID列表不能为空");
        }
        
        // 批量删除
        boolean success = this.removeByIds(ids);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "批量删除用户表（存储用户基础信息）失败");
        }
    }

    // 关联关系查询方法将在后续版本中支持

    /**
     * 实体转VO
     */
    private UserVO convertToVO(User entity) {
        if (entity == null) {
            return null;
        }
        
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * DTO转实体
     */
    private User convertToEntity(UserDTO dto) {
        if (dto == null) {
            return null;
        }
        
        User entity = new User;
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 验证DTO参数
     */
    private void validateDTO(UserDTO dto) {
        if (dto == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "用户表（存储用户基础信息）信息不能为空");
        }
        
        // 必填字段验证
        if (!StringUtils.hasText(dto.getUsername())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "用户名（唯一，用于登录）不能为空");
        }
        if (!StringUtils.hasText(dto.getPhone())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "手机号（唯一，用于登录/验证）不能为空");
        }
        if (!StringUtils.hasText(dto.getPassword())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "密码（加密存储，如BCrypt算法）不能为空");
        }
    }
}
